<template>
  <div>
    <div class="detail" v-if="type == 'add' || type == 'edit'">
      <div style="width: 420px">
        <div class="sign">注：本页面富文本中上传的视频无法在小程序中显示</div>
        <el-form
          ref="form_task"
          :model="form"
          :rules="rules"
          :label-width="selectedType == 1 ? '100px' : '88px'"
        >
          <el-form-item
            :label="`${selectedType == 1 ? '任务学时' : '学时'}`"
            prop="studyHour"
          >
            <el-input-number
              controls-position="right"
              :min="0"
              v-model="form.studyHour"
              placeholder="请输入"
            />
            时
          </el-form-item>
          <el-form-item
            v-if="selectedType == 1"
            label="任务描述"
            prop="description"
          >
            <el-input
              maxlength="2000"
              class="edit_texteara"
              show-word-limit
              :autosize="{ minRows: 5, maxRows: 8 }"
              v-model="form.description"
              type="textarea"
              :placeholder="
                $route.query.modelType == 0
                  ? '请输入任务描述'
                  : '对任务发生时间、地点等背景信息进行陈述，创设学习情况，对实施计划人、工作要求、工作流程进行说明。'
              "
            />
          </el-form-item>
          <el-form-item
            :label="`${selectedType == 1 ? '任务目标' : '目标'}`"
            prop="target"
          >
            <!--            备注：由于新版本富文本回车限制，经项目经理同意，此处富文本采用旧版本不包含录入公式功能 20250716 -->
            <div class="edit_texteara">
              <wangEditor
                v-if="selectedType == 1"
                :placeholder="
                  $route.query.modelType == 0
                    ? '请输入任务目标'
                    : '按照工作过程进行描述，结合学生情况对任务学习目标进行补充和完善。'
                "
                :uuid="courseForm.dirName"
                v-model="form.target"
                :courseId="courseForm.courseId"
                @turnWord="uploadWordToNode($event, 'target')"
              />
              <wangEditor
                v-if="selectedType == 2"
                :placeholder="
                  $route.query.modelType == 0
                    ? '请输入目标'
                    : ' 对标学习任务教学活动策划、教学进度计划等课程文件，并结合学情进行设计。包括专业能力、通用能力、思政目标等内容，建议三者融合撰写。'
                "
                :uuid="courseForm.dirName"
                v-model="form.target"
                :courseId="courseForm.courseId"
                @turnWord="uploadWordToNode($event, 'target')"
              />
            </div>
          </el-form-item>
          <el-form-item label="其他" prop="target">
            <div class="edit_texteara">
              <wangEditor
                :uuid="courseForm.dirName"
                v-model="form.other"
                :courseId="courseForm.courseId"
                @turnWord="uploadWordToNode($event, 'other')"
              />
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div
        class="param_item"
        v-for="(item, index) in form.ccCourseIndexParamList"
        :key="index"
      >
        <div class="btns">
          <el-button
            @click="delParamItem(item, index)"
            type="danger"
            icon="el-icon-delete"
            circle
          ></el-button>
        </div>
        <div class="param_item_content">
          <el-input
            class="param_item_content_label"
            v-model="item.label"
            clearable
            size="small"
            placeholder="请输入字段名称"
          />
          <el-input
            maxlength="500"
            class="edit_texteara"
            show-word-limit
            :autosize="{ minRows: 5, maxRows: 8 }"
            v-model="item.value"
            type="textarea"
            :placeholder="`请输入${item.label}`"
          />
        </div>
      </div>
      <div class="add_label">
        <el-button type="primary" @click="showAddLabel = true">
          <i class="el-icon-plus"></i> 增加字段
        </el-button
        >
      </div>
    </div>
    <div v-else class="lookDetail">
      <div class="flex item" v-if="form.studyHour">
        <div class="item_label">
          {{ selectedType == 1 ? '任务学时' : '学时' }}
        </div>
        <div style="white-space: pre-wrap" class="item_value">
          {{ form.studyHour ? form.studyHour : 0 }} 时
        </div>
      </div>
      <div v-if="selectedType == 1 && form.description" class="flex item">
        <div class="item_label">任务描述</div>
        <div
          style="white-space: pre-wrap"
          class="item_value"
          v-html="form.description"
        ></div>
      </div>
      <div class="flex item" v-if="form.target">
        <div class="item_label">
          {{ selectedType == 1 ? '任务目标' : '目标' }}
        </div>
        <div
          style="white-space: pre-wrap"
          class="item_value"
          v-html="form.target"
        ></div>
      </div>
      <div class="flex item" v-if="form.other">
        <div class="item_label">其他</div>
        <div
          style="white-space: pre-wrap"
          class="item_value"
          v-html="form.other"
        ></div>
      </div>
      <div
        class="flex item"
        v-for="(item, index) in form.ccCourseIndexParamList"
        :key="index"
      >
        <div class="item_label">
          {{ item.label }}
        </div>
        <div
          style="white-space: pre-wrap"
          class="item_value"
          v-html="item.value"
        ></div>
      </div>
      <div
        v-if="
          !form.other &&
          !form.studyHour &&
          !form.target &&
          !form.description &&
          form.ccCourseIndexParamList.length == 0
        "
      >
        <el-empty description="暂无信息~" style=""></el-empty>
      </div>
    </div>
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      title="增加字段"
      :visible="showAddLabel"
      width="500px"
      append-to-body
      @close="cancelDia()"
    >
      <el-form
        @submit.native.prevent
        ref="labelForm"
        :model="addLabelForm"
        :rules="labelFormRules"
        label-width="120px"
      >
        <el-form-item label="字段名称" prop="label">
          <el-input
            size="small"
            clearable
            v-model="addLabelForm.label"
            placeholder="请输入字段名称"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-preventReClick @click="cancelDia">取 消</el-button>
        <el-button v-preventReClick type="primary" @click="submitLabelForm"
        >确 定
        </el-button
        >
      </div>
    </el-dialog>
    <div class="detailbottom flexEnd" v-if="type == 'audit'">
      <el-button v-preventReClick type="primary" @click="goBack">
        退 出
      </el-button>
      <el-button v-preventReClick @click="reject" type="danger">
        驳回
      </el-button>
      <el-button v-preventReClick @click="audit" type="primary">
        通过审核
      </el-button>
    </div>
    <div class="detailbottom flexEnd" v-else>
      <el-button
        v-preventReClick
        type="primary"
        v-if="type == 'add' || type == 'edit'"
        @click="submitForm()"
      >
        保 存
      </el-button>
      <el-button
        v-preventReClick
        type="primary"
        v-if="type == 'detail'"
        @click="goBack"
      >
        退 出
      </el-button>
    </div>
    <rejectDia
      type="1"
      :open.sync="rejectOpen"
      :propform="courseForm"
      @refresh="goBack"
    ></rejectDia>
  </div>
</template>

<script>
import {
  getCourseIndexDetial,
  addProperties,
  deleteProperties,
  editCourseIndex,
  editCourseStatus
} from '@/api/course/course'
import { getPost_school } from '@/api/schoolOrganization/schoolInfo'
import wangEditor from '@/components/wangEditor.vue'
import rejectDia from './rejectDia.vue'

export default {
  components: {
    wangEditor,
    rejectDia
  },
  props: {
    //判断修改  还是详情 还是新增
    type: String,
    //判断任务还是目录   1  任务    2  目录
    selectedType: [String, Number],
    //课程信息
    courseForm: [Object],

    selectedTaskId: [String, Number],
    //判断当前选中的  tabs
    tabIndex: [String, Number],
    //之前被删除的id>>>>>>>>>>>>>deleteId
    deleteId: [String, Number],
    status: {
      type: [String, Number]
    },
    enterType: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      info: {},
      rejectOpen: false,
      // 表单参数
      form: {
        studyHour: undefined,
        target: '<p><br></p>',
        other: '<p><br></p>',
        description: '',
        ccCourseIndexParamList: []
      },
      showAddLabel: false,
      // 表单校验
      rules: {
        labelFormRules: {}
      },
      addLabelForm: {
        label: '',
        value: ''
      },
      // 表单校验
      labelFormRules: {
        label: [
          { required: true, message: '字段名称不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
  },
  beforeDestroy() {
    if (
      (this.type == 'add' || this.type == 'edit') &&
      this.tabIndex == 1 &&
      this.form.id
    ) {
      this.submitForm()
    }
  },
  watch: {
    //监听form.id   来判断同组件切换时   保存上一个内容
    form: {
      handler(newValue, oldValue) {
        //判断有旧的form.id   说明是同组件切换   没有则证明是初次加载该组件
        //判断有旧的form.id  是否变化   有变化说明是组件切换了数据  将旧的id数据保存
        //deleteId>>>>>>>>>>删除过的 树节点id  如果oldValue.id==deleteId 说明oldValue节点已经被删除了，所以不用保存oldValue数据
        if (
          oldValue.id != newValue.id &&
          oldValue.id &&
          this.tabIndex == 1 &&
          this.deleteId != oldValue.id
        ) {
          this.submitForm(oldValue)
        }
      }
    },
    selectedTaskId: {
      handler() {
        this.reset()
        this.getInfo()
        if (this.type == 'audit') {
          this.getSchoolInfo()
        }
      },
      immediate: true
    }
  },
  methods: {
    /** 获取学校信息 */
    async getSchoolInfo() {
      let res = await getPost_school()
      const { code, data } = res
      if (code == 200) {
        this.info = data
      }
    },
    /* 驳回 */
    reject() {
      this.rejectOpen = true
    },
    /* 通过审核 */
    audit() {
      this.$confirm(`是否确认通过审核?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const loading = this.$loading({
            lock: true,
            text: '正在处理…',
            spinner: 'el-icon-loading',
            background: 'rgba(255, 255, 255, 0.6)'
          })
          //当分院审核时（this.status == "30"）
          if (this.status == '30') {
            //type  类型:0-高用,1-停用,2-提交审校,了-撤回审校,4-分院审校,5-学校审校,6-驳回
            let params = {
              type: 4,
              courseId: this.form.courseId
            }
            let res = await editCourseStatus(params.type, params.courseId)
            if (res.code == 200) {
              loading.close()
              // 判断审核配置  是否需要学校审核   不需要学校审核则分院直接审核通过
              if (this.info.courseNeedCheckSchool == 1) {
                this.$modal.msgSuccess('审核已通过，待学校审核')
              } else {
                //分院直接审核通过
                this.$modal.msgSuccess('通过审核成功')
              }
              this.$store.dispatch(
                'tagsView/delView',
                this.$router.currentRoute
              )
              setTimeout(() => {
                this.$router.go(-1)
              }, 100)
            } else {
              loading.close()
            }
          } else {
            //type  类型:0-高用,1-停用,2-提交审校,了-撤回审校,4-分院审校,5-学校审校,6-驳回
            let params = {
              type: 5,
              courseId: this.form.courseId
            }
            let res = await editCourseStatus(params.type, params.courseId)
            if (res.code == 200) {
              loading.close()
              if (this.status == '50') {
                this.$EventBus.$emit('courseStatusRefresh', true)
              }
              this.$modal.msgSuccess('通过审核成功')
              this.$store.dispatch(
                'tagsView/delView',
                this.$router.currentRoute
              )
              setTimeout(() => {
                this.$router.go(-1)
              }, 100)
            } else {
              loading.close()
            }
          }
        })
        .catch(() => {
        })
    },

    delParamItem(item, index) {
      this.$confirm(`确认删除名为【${item.label}】的自定义字段？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const loading = this.$loading({
            lock: true,
            text: '正在处理...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          let res = await deleteProperties(item.id)
          if (res.code == 200) {
            loading.close()
            this.$modal.msgSuccess('删除成功！')
            this.form.ccCourseIndexParamList.splice(index, 1)
          } else {
            loading.close()
          }
        })
        .catch(() => {
          this.$modal.msgInfo('已取消')
        })
    },
    uploadWordToNode(formData, item) {
      this.form[item] += formData
    },
    /* 获取章节信息(分草稿和正式课程) */
    async getInfo() {
      let res = await getCourseIndexDetial(this.selectedTaskId)
      const { code, data } = res
      if (code == 200) {
        this.form = data
        this.form.target = data.target ? data.target : '<p><br></p>'
        this.form.other = data.other ? data.other : '<p><br></p>'

      }
    },
    /** 提交按钮 修改章节信息*/
    submitForm(oldValue) {
      if (this.type == 'edit' || this.type == 'add') {
        this.$refs['form_task'].validate(async(valid) => {
          if (valid) {
            let params
            //有oldValue   说明是切换组件时保存上一个组件数据   否侧时提交当前组件数据
            if (oldValue) {
              params = {
                ...oldValue
              }
            } else {
              params = {
                ...this.form
              }
            }
            delete params.name
            delete params.sort
            let res = await editCourseIndex(params)
            const { code } = res
            if (code == 200) {
              this.$modal.msgSuccess('保存成功')
            }
          }
        })
      }
    },
    // 表单重置
    reset() {
      this.form = {
        studyHour: undefined,
        target: '<p><br></p>',
        description: '',
        other: '<p><br></p>',
        ccCourseIndexParamList: []
      }
      // this.resetForm("form");
    },
    cancelDia() {
      this.addLabelForm = {
        label: '',
        value: ''
      }
      this.resetForm('labelForm')
      this.showAddLabel = false
    },
    submitLabelForm() {
      this.$refs['labelForm'].validate(async(valid) => {
        if (valid) {
          let params = {
            courseId: this.courseForm.courseId,
            label: this.addLabelForm.label,
            value: this.addLabelForm.value,
            indexId: this.selectedTaskId,
            sort: this.form.ccCourseIndexParamList
              ? this.form.ccCourseIndexParamList.length + 1
              : 1,
            temporaryState: 0
          }
          let res = await addProperties(params)
          if (res.code == 200) {
            let obj = {
              ...params,
              id: res.data
            }
            this.$modal.msgSuccess('新增成功')
            this.form.ccCourseIndexParamList.push(obj)
            this.cancelDia()
          }
        }
      })
    },
    goBack() {
      if (this.enterType == 'manager') {
        this.$store.dispatch('tagsView/delView', this.$router.currentRoute)
        setTimeout(() => {
          this.$router.go(-1)
        }, 100)
      } else {
        this.$router.go(-1)
      }
    }
  }
}
</script>
<style scoped lang="scss">
.lookDetail {
  padding: 24px 0 0 40px;
  border-top: 1px solid #ebebeb;
  box-sizing: border-box;
  height: calc(100vh - 310px + 77px - 72px);
  overflow: auto;

  .item {
    margin-bottom: 32px;

    .item_label {
      margin-right: 32px;
      font-size: 16px;
      font-family: PingFangSC-Regular, PingFang SC, sans-serif;
      font-weight: 400;
      color: #999999;
      line-height: 22px;
    }

    .item_value {
      width: 696px;
      font-size: 16px;
      font-family: PingFangSC-Regular, PingFang SC, sans-serif;
      font-weight: 400;
      color: #333333;
      line-height: 22px;
      white-space: pre-wrap;
      word-wrap: break-word;
    }
  }
}

.detailbottom {
  border-top: 1px solid #ebebeb;
  height: 72px;
  box-sizing: border-box;
  padding: 0 19px 0 37px;
  align-items: center;

  ::v-deep .el-button {
    padding: 0 24px;
    font-size: 16px;
    font-family: PingFangSC-Regular, PingFang SC, sans-serif;
    font-weight: 400;
    border-radius: 8px;
    line-height: 38px;
    height: 40px;
  }
}

.detail {
  padding: 32px 0 0 0;
  box-sizing: border-box;
  height: calc(100vh - 310px + 77px - 72px);
  overflow: auto;
}

.edit_texteara {
  width: 640px;
}

.add_label {
  width: 100%;
  display: flex;
  justify-content: center;
  margin-bottom: 20px;

  .el-icon-plus {
    font-style: normal;
  }
}

.param_item {
  margin: 0 0 20px 38px;

  .btns {
    width: 100%;
    display: flex;
    justify-content: flex-end;
    padding: 0 40px 10px 0;
    box-sizing: border-box;
  }

  &_content {
    width: 100%;
    display: flex;
    align-items: flex-start;

    &_label {
      width: 140px;
      margin-right: 20px;
    }
  }
}

::v-deep .el-icon-delete,
::v-deep .el-icon-circle-close {
  font-style: normal;
}

//富文本回显样式
::v-deep h5,
.h5 {
  font-size: 14px;
}

::v-deep h4,
.h4 {
  font-size: 16px;
  font-weight: bold;
}

::v-deep h3,
.h3 {
  font-size: 18px;
  font-weight: bold;
}

::v-deep h2,
.h2 {
  font-size: 20px;
  font-weight: bold;
}

::v-deep h1,
.h1 {
  font-size: 22px;
  font-weight: bold;
}

::v-deep i {
  font-style: italic;
}

::v-deep .w-e-toolbar .w-e-menu i {
  font-style: normal;
}

::v-deep ol {
  list-style-type: decimal;
}

/* ul ol 样式 */
::v-deep ol {
  margin: 10px 0 10px 22px;
  list-style-type: decimal;
}

::v-deep ul {
  margin: 10px 0 10px 22px;
  list-style-type: disc;
}

/* table 样式 */
::v-deep table {
  border-top: 1px solid #ccc;
  border-left: 1px solid #ccc;
}

::v-deep table td,
::v-deep table th {
  border-bottom: 1px solid #ccc;
  border-right: 1px solid #ccc;
  padding: 3px 5px;
  height: 32px;
}

::v-deep table th {
  border-bottom: 2px solid #ccc;
  text-align: center;
  background-color: #f1f1f1;
}

/* blockquote 样式 */
::v-deep blockquote {
  display: block;
  border-left: 8px solid #d0e5f2;
  padding: 5px 10px;
  margin: 10px 0;
  line-height: 1.4;
  min-height: 24px;
  font-size: 100%;
  background-color: #f1f1f1;
}

/* code 样式 */
::v-deep code {
  display: inline-block;
  background-color: #f1f1f1;
  border-radius: 3px;
  padding: 3px 5px;
  margin: 0 3px;
}

::v-deep pre code {
  display: block;
}

::v-deep a {
  text-decoration: underline;
  color: #5592e5;
}

::v-deep .w-e-text-placeholder {
  top: 10px !important;
}

.sign {
  color: #ff9b0f;
  font-size: 14px;
  padding: 0 0 20px 48px;
  box-sizing: border-box;
}
</style>
